package cn.actoncode.boot.framework.common.util.file;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MyFileUtil {

    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        try {
            File file = File.createTempFile(RandomStringUtils.randomAlphanumeric(18), suffix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载url文件
     * @param url
     * @param file
     * @throws IOException
     */
    public static void copyURLToFile(URL url, File file) throws IOException {
        // 创建文件输出流
        FileOutputStream fs = new FileOutputStream(file);
        // 读取文件
        readFile(0, getFileResourceLength(url), url, fs);
        fs.close();
    }

    /**
     * 下载url文件
     * @param url
     * @param file
     * @throws IOException
     */
    public static void copyURLToFile(URL url, File file, long length) throws IOException {
        // 创建文件输出流
        FileOutputStream fs = new FileOutputStream(file);
        // 读取文件
        readFile(0, length, url, fs);
        fs.close();
    }

    private static void readFile(long start, long end, URL url, FileOutputStream fs) throws IOException {
        // 设置读取链接的范围
        String range = "bytes=" + start + "-" + end;
        // 打开链接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("RANGE", range);
        connection.setRequestProperty("User-Agent", "NetFox");
        connection.setRequestMethod("GET");
        connection.setReadTimeout(60*1000);
        connection.setConnectTimeout(60*1000);
        connection.connect();// 连接网络资源
        // 输入流
        InputStream inStream = connection.getInputStream();
        LimitInputStream limitInputStream = new LimitInputStream(inStream, new BandwidthLimiter(2048));
        // 总共读取了多少
        long bytesum = start;
        int byteread = 0;

        byte[] buffer = new byte[1204];
        while ((byteread = limitInputStream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
        }
        inStream.close();
        connection.disconnect();
        // 总共读取的长度小于文件长度则重本次最终长度开始重新读取
        if (bytesum < end) {
            readFile(bytesum, end, url, fs);
        }
    }

    private static long getFileResourceLength(URL url) throws IOException {
        URLConnection urlConnection=url.openConnection();
        urlConnection.connect();
        return urlConnection.getContentLength();
    }
}
